<template>
    <div id="horizontalbarchart">
        <div id="horizontalbar"></div>
        <div id="horizontalbarData">
          <el-input type="textarea" :rows="2"  v-model="horizontalBarDataS" @change="dataChange">
           </el-input>
          <el-button type="primary" plain @click="barSort">Sort</el-button>
        </div>
    </div>
</template>
<script>
import {HorizontalBarChart} from './HorizontalBarChart'
export default {
  data () {
    return {
      horizontalBarChart: '',
      horizontalBarData: []
    }
  },
  created () {
    this.horizontalBarChart = new HorizontalBarChart('horizontalbar')
    this.getData()
  },
  mounted () {
    this.horizontalBarChart.data = this.horizontalBarData
    this.horizontalBarChart.xLabel = 'Num'
    this.horizontalBarChart.yLabel = 'cate'
    this.horizontalBarChart.draw()
  },
  computed: {
    horizontalBarDataS: {
      get: function () {
        let valueString = ''
        for (let i = 0; i < this.horizontalBarData.length - 1; ++i) {
          valueString += this.horizontalBarData[i].name + ':' + this.horizontalBarData[i].value + ','
        }
        valueString += this.horizontalBarData[this.horizontalBarData.length - 1].name + ':' +
          this.horizontalBarData[this.horizontalBarData.length - 1].value
        return valueString
      },
      set: function (d) {
        let values = d.split(',')
        this.horizontalBarData = []
        for (let i = 0; i < values.length; ++i) {
          this.horizontalBarData.push({
            name: parseInt(values[i].split(':')[0]),
            value: parseInt(values[i].split(':')[1])
          })
        }
      }
    }
  },
  methods: {
    getData () {
      let num = parseInt(Math.random() * 5 + 15)
      for (let i = 0; i < num; ++i) {
        this.horizontalBarData.push({
          name: i,
          value: parseInt(Math.random() * 40)
        })
      }
    },
    barSort () {
      this.horizontalBarData.sort((a, b) => {
        return a.value - b.value
      })
      this.horizontalBarChart.data = this.horizontalBarData
      this.horizontalBarChart.update()
    },
    dataChange () {
      this.horizontalBarChart.data = this.horizontalBarData
      this.horizontalBarChart.update()
    }
  }
}
</script>
<style scoped>
#horizontalbarchart {
    height: 100%;
    width: 100%;
}
#horizontalbar {
    height: 70%;
    width: 100%;
}
#horizontalbarData {
    height: 30%;
    width: 100%;
}
</style>
